package com.zsj.comminlibrary.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;

public class LoadingRelativeLayout extends RelativeLayout {
    private Context mContext;
    private float radio = 8;
    private int color = 0xff000000;
    private long time = 3000;
    private Paint mPaint;
    private float mRight;
    private Thread mAnimThread;
    private int mWidth;
    private int mHeight;

    public LoadingRelativeLayout(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public LoadingRelativeLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    public LoadingRelativeLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    public void startAnim() {
        mAnimThread = new Thread(() -> {
            float count = mWidth / ((1500f / 1000) * 60);
            mRight = 0;
            while (true) {
                mRight += count;
                if (mRight < mWidth) {
                    mHandler.sendEmptyMessage(1);
                } else {
                    mRight = 0;
                    mHandler.sendEmptyMessage(1);
                    break;
                }
                try {
                    Thread.sleep(16);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });
        mAnimThread.start();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        mWidth = getWidth();
        mHeight = getHeight();
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        canvas.drawRoundRect(0, 0, mRight, mHeight, radio, radio, mPaint);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            invalidate();
        }
    };

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(color);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(12);
        setWillNotDraw(false);
    }

    public float getRadio() {
        return radio;
    }

    public void setRadio(float radio) {
        this.radio = radio;
    }

    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        mPaint.setColor(color);
        this.color = color;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }
}
